package com.by.token;

import com.auth0.jwt.JWT;
import com.auth0.jwt.JWTVerifier;
import com.auth0.jwt.algorithms.Algorithm;
import com.auth0.jwt.exceptions.JWTDecodeException;
import com.auth0.jwt.exceptions.TokenExpiredException;
import com.auth0.jwt.interfaces.Claim;
import com.auth0.jwt.interfaces.DecodedJWT;
import com.by.auto.TokenProperties;
import com.by.bean.UserInfo;
import com.by.context.UserContext;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.stereotype.Component;

import java.util.Date;
import java.util.HashMap;
import java.util.Map;

/**
 * date 2025/2/10 14:01
 * author bjj
 * decoration
 * version 1.0
 * since jdk11
 */

public class TokenTemplate {
    TokenProperties tokenProperties;

    public TokenTemplate(TokenProperties tokenProperties) {
        this.tokenProperties = tokenProperties;
    }

    /**
     * 生成token
     *
     * @param payload
     * @return
     */
    public String generateToken(Map payload) {
        String token = JWT.create().withHeader(getHeader())
                .withPayload(payload)
                .withIssuer("by")
                .withExpiresAt(getExpireDate())
                .sign(Algorithm.HMAC256(tokenProperties.getSecret()));
        return token;
    }

    /**
     * 验证token
     *
     * @param token
     * @return 1 token无效  2 token过期  3 token有效
     */
    public ValidResult valid(String token) {
        JWTVerifier verifier = JWT.require(Algorithm.HMAC256(tokenProperties.getSecret()))
                .build();
        DecodedJWT jwt = null;
        try {
            jwt = verifier.verify(token);
        } catch (JWTDecodeException e) {
            return ValidResult.INVALID;
        } catch (TokenExpiredException e) {
            return ValidResult.EXPIRE;
        }
        Map<String, Claim> payload = jwt.getClaims();
        int id = payload.get("id").asInt();
        String username = payload.get("username").asString();
        int type = payload.get("type").asInt();
        Claim claim = payload.get("roles");
        // 添加角色信息校验
        if (claim == null || claim.isNull()) {
            return ValidResult.INVALID; // 或抛出自定义异常
        }
        String role = claim.toString();
        // 添加空字符串校验
        if (role == null || role.isEmpty()) {
            return ValidResult.INVALID;
        }
        String[] gdt = role.split("\"");
        UserInfo userInfo = new UserInfo(id, username, Integer.parseInt(gdt[1]), type);
        UserContext.set(userInfo);
        return ValidResult.VALID;
    }

    Date getExpireDate() {
        return new Date(System.currentTimeMillis() + tokenProperties.getValidTime());
    }

    Map getHeader() {
        Map<String, String> map = new HashMap<>();
        map.put("type", "JWT");
        map.put("alg", "HMAC256");
        return map;
    }

}
